<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :close-on-click-modal="false">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="资产名称" prop="assetName">
        <el-input v-model="formData.assetName" placeholder="请输入资产名称" />
      </el-form-item>
      <el-form-item label="资产编码" prop="assetCode">
        <el-input v-model="formData.assetCode" placeholder="请输入资产编码" />
      </el-form-item>
      <el-form-item label="资产型号" prop="model">
        <el-input v-model="formData.model" placeholder="请输入资产型号" />
      </el-form-item>
      <el-form-item label="资产分类" prop="assetCategory">
        <el-input v-model="formData.assetCategory" placeholder="请输入资产分类" />
      </el-form-item>
      <el-form-item label="资产品牌" prop="assetBrand">
        <el-input v-model="formData.assetBrand" placeholder="请输入资产品牌" />
      </el-form-item>
      <el-form-item label="质保日期" prop="warrantyDate">
        <el-date-picker
          v-model="formData.warrantyDate"
          type="date"
          value-format="x"
          placeholder="选择质保日期"
        />
      </el-form-item>

      <el-form-item label="使用人员" prop="userId">
        <UserSelect @node-change="handleNodeChange" v-model="formData.userId"  />
      </el-form-item>

      <!-- <el-form-item label="购买价格" prop="purchasePrice">
        <el-input v-model="formData.purchasePrice" placeholder="请输入购买价格" />
      </el-form-item> -->
      <!-- <el-form-item label="购买日期" prop="purchaseDate">
        <el-date-picker
          v-model="formData.purchaseDate"
          type="date"
          value-format="x"
          placeholder="选择购买日期"
        />
      </el-form-item> -->
      <!-- <el-form-item label="年折旧率(%)" prop="annualDepreciationRate">
        <el-input v-model="formData.annualDepreciationRate" placeholder="请输入购买日期" />
      </el-form-item> -->
      <el-form-item label="资产单位" prop="assetUnit">
        <el-select v-model="formData.assetUnit" placeholder="请选择资产单位">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.OA_ASSET_UNIT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="资产状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_ASSET_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="资产来源" prop="source">
        <el-radio-group v-model="formData.source">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_ASSET_SOURCE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="放置地址" prop="location">
        <el-input v-model="formData.location" placeholder="请输入放置地址" />
      </el-form-item>
      <el-form-item label="备注" prop="description">
        <el-input
          v-model="formData.description"
          style="width: 100%;"
          :rows="4"
          type="textarea"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { AssetInfoApi, AssetInfoVO } from '@/api/oa/assetinfo'
import UserSelect from '@/views/system/user/UserSelect.vue'

/** 资产信息 表单 */
defineOptions({ name: 'AssetInfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  assetCode: undefined,
  assetName: undefined,
  model: undefined,
  assetCategory: undefined,
  assetBrand: undefined,
  warrantyDate: undefined,
  userId: undefined,
  purchasePrice: undefined,
  purchaseDate: undefined,
  annualDepreciationRate: undefined,
  assetUnit: undefined,
  status: undefined,
  source: undefined,
  location: undefined,
  description: undefined
})
const formRules = reactive({
  assetCode: [{ required: true, message: '资产编码不能为空', trigger: 'blur' }],
  assetName: [{ required: true, message: '资产名称不能为空', trigger: 'blur' }],
  // assetCategory: [{ required: true, message: '资产分类不能为空', trigger: 'change' }],
  // assetBrand: [{ required: true, message: '资产品牌不能为空', trigger: 'change' }],
  assetUnit: [{ required: true, message: '资产单位不能为空', trigger: 'change' }],
  status: [{ required: true, message: '资产状态不能为空', trigger: 'change' }],
  source: [{ required: true, message: '资产来源不能为空', trigger: 'change' }],
  // purchasePrice: [{ required: true, message: '购买价格不能为空', trigger: 'blur' }],
  // warrantyDate: [{ required: true, message: '质保到期日不能为空', trigger: 'change' }],
  model: [{ required: true, message: '资产型号不能为空', trigger: 'blur' }],
  // purchaseDate:  [{ required: true, message: '购买日期不能为空', trigger: 'change' }],
  // annualDepreciationRate: [{ required: true, message: '年折旧率(%)不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const generateAssetCode = (): string => {
  // 获取当前日期时间戳（格式：YYYYMMDDHHMMSS）
  const timestamp = new Date().toISOString().replace(/[-T:.Z]/g, '').substring(0, 14);

  // 生成三位随机数（XXX）
  const randomPart = Math.floor(Math.random() * 1000).toString().padStart(3, '0');

  // 拼接成最终的编码格式：ZCYYYYMMDDHHMMSSXXX
  return `ZC${timestamp}${randomPart}`;
}


/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true;
  dialogTitle.value = t('action.' + type);
  formType.value = type;
  resetForm();

  if (type === 'create') {
    formData.value.assetCode = generateAssetCode();
  }

  if (id) {
    formLoading.value = true;
    try {

      formData.value = await AssetInfoApi.getAssetInfo(id);
    } finally {
      formLoading.value = false;
    }
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AssetInfoVO
    if (formType.value === 'create') {
      await AssetInfoApi.createAssetInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await AssetInfoApi.updateAssetInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    assetCode: undefined,
    assetName: undefined,
    model: undefined,
    assetCategory: undefined,
    assetBrand: undefined,
    warrantyDate: undefined,
    userId: undefined,
    purchasePrice: undefined,
    purchaseDate: undefined,
    annualDepreciationRate: undefined,
    assetUnit: undefined,
    status: undefined,
    source: undefined,
    location: undefined,
    description: undefined
  }
  formRef.value?.resetFields()
}
/** 员工被点击事件 */
const handleNodeChange = async (row) =>{
  console.log('【UserSelect】选中用户对象:', row) // 打印完整对象
  console.log('用户ID:', row?.id)
  console.log('用户昵称:', row?.nickname)
  formData.value.userId = row.id
  formData.value.nickName = row.nickname
}
</script>
